<template>
  <view class="local-services-container">
    <!-- 服务分类网格 (3x5 layout) -->
    <view class="categories-container">
      <view class="categories-grid">
        <view 
          v-for="category in categories" 
          :key="category.id" 
          class="category-item"
          :class="{ 'category-active': selectedCategory && selectedCategory.id === category.id }"
          @click="handleCategoryClick(category)"
        >
          <view class="category-icon">{{ category.icon }}</view>
          <text class="category-name">{{ category.name }}</text>
        </view>
      </view>
    </view>

    <!-- 地理位置筛选 -->
    <view class="location-filter">
      <view class="filter-section">
        <text class="filter-label">选择地区</text>
        <view class="pickers-row">
          <view class="picker-wrapper">
            <picker
              :value="selectedProvinceIndex"
              :range="provinces"
              @change="onProvinceChange"
              class="form-picker"
            >
              <view class="picker-content">
                <text class="picker-text" :class="{ placeholder: selectedProvinceIndex === -1 }">{{ provinces[selectedProvinceIndex] || '选择省份' }}</text>
                <text class="arrow">></text>
              </view>
            </picker>
          </view>
          <view class="picker-wrapper">
            <picker
              :value="selectedCityIndex"
              :range="cities"
              @change="onCityChange"
              class="form-picker"
            >
              <view class="picker-content">
                <text class="picker-text" :class="{ placeholder: selectedCityIndex === -1 || cities[selectedCityIndex] === '请先选择省份' }">{{ cities[selectedCityIndex] || '选择城市' }}</text>
                <text class="arrow">></text>
              </view>
            </picker>
          </view>
        </view>
      </view>
    </view>

    <!-- 服务列表 -->
    <view class="services-container" v-if="selectedCategory">
      <view class="services-header">
        <text class="header-title">{{ selectedCategory.name }}服务</text>
        <text class="header-count" v-if="services.length > 0">({{ services.length }}个)</text>
      </view>
      
      <view class="services-list">
        <view 
          v-for="service in services" 
          :key="service.id" 
          class="service-item"
          @click="goToServiceDetail(service)"
        >
          <image 
            :src="service.images && service.images.length > 0 ? service.images[0] : '/static/images/default-service.jpg'" 
            class="service-image" 
            mode="aspectFill"
          />
          <view class="service-info">
            <view class="service-header">
              <view class="service-title">{{ service.title }}</view>
              <view class="service-tags">
                <text class="tag verified" v-if="service.audit_status === 'APPROVED'">认证</text>
                <text class="tag deposit" v-if="service.deposit_required > 0">保证金</text>
              </view>
            </view>
            <view class="service-contact">
              <text class="contact-label">联系人：</text>
              <text class="contact-name">{{ service.user?.nickname || '匿名用户' }}</text>
            </view>
            <view class="service-location">
              <view class="location-icon">📍</view>
              <text class="location-text">{{ service.city }}</text>
            </view>
            
            <!-- 互动操作区域 -->
            <view class="service-actions">
              <view class="action-stats">
                <view class="stat-item" v-if="service.comment_count > 0">
                  <text class="stat-icon">💬</text>
                  <text class="stat-count">{{ service.comment_count }}</text>
                </view>
              </view>
              
              <view class="like-action" @click.stop="toggleServiceLike(service)">
                <view class="like-button" :class="{ 'liked': service.is_liked }">
                  <text class="like-icon">♥</text>
                  <text class="like-count">{{ service.like_count || 0 }}</text>
                </view>
              </view>
            </view>
          </view>
        </view>
      </view>
      
      <view class="no-services" v-if="!loading && services.length === 0">
        <text class="no-services-text">暂无相关服务</text>
      </view>
    </view>

    <!-- 底部功能按钮 -->
    <view class="bottom-actions">
      <button class="action-btn primary" @click="goToPublish">
        一手加入
      </button>
      <button class="action-btn secondary" @click="goToMyListings">
        我的发布
      </button>
    </view>

    <!-- 加载状态 -->
    <view v-if="loading" class="loading-overlay">
      <view class="loading-content">
        <text class="loading-text">加载中...</text>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import { onShow } from '@dcloudio/uni-app'
import { localServiceAPI } from '@/utils/api.js'
import { getProvinces, getCitiesByProvince } from '@/utils/areaData.js'
import CreditChecker from '@/utils/creditChecker.js'

// 响应式数据
const categories = ref([])
const services = ref([])
const loading = ref(true)
const selectedCategory = ref(null)

// 省市数据
const provinces = getProvinces()
const selectedProvinceIndex = ref(-1)
const cities = ref(['请先选择省份'])
const selectedCityIndex = ref(-1)
const currentProvince = ref('')
const currentCity = ref('')

// 页面首次加载
onMounted(() => {
  loadCategories()
})

// 页面显示时（包括从其他页面返回）
onShow(() => {
  // 检查是否有从详情页返回的更新数据
  const pages = getCurrentPages()
  const currentPage = pages[pages.length - 1]
  
  if (currentPage.data && currentPage.data.serviceUpdate) {
    const updateData = currentPage.data.serviceUpdate
    
    // 找到对应的服务并更新数据
    const serviceIndex = services.value.findIndex(s => s.id === updateData.id)
    if (serviceIndex !== -1) {
      services.value[serviceIndex].like_count = updateData.like_count
      services.value[serviceIndex].is_liked = updateData.is_liked
      services.value[serviceIndex].comment_count = updateData.comment_count
      console.log('从详情页更新服务数据:', updateData)
    }
    
    // 清除更新标记
    delete currentPage.data.serviceUpdate
  }
})

// 监听地理位置变化
watch([currentProvince, currentCity, selectedCategory], () => {
  if (selectedCategory.value) {
    loadServices()
  }
}, { deep: true })

// 方法定义
/**
 * 加载服务分类
 */
const loadCategories = async () => {
  try {
    loading.value = true
    const result = await localServiceAPI.getCategories()
    
    if (result.success) {
      // 使用默认分类数据，确保是3x5布局（15个分类）
      categories.value = result.data && result.data.length > 0 ? result.data : getDefaultCategories()
    } else {
      categories.value = getDefaultCategories()
    }
    
    // 默认选择第一个类型
    if (categories.value && categories.value.length > 0) {
      selectedCategory.value = categories.value[0]
      loadServices()
    }
  } catch (error) {
    console.error('加载服务分类失败:', error)
    categories.value = getDefaultCategories()
    
    // 默认选择第一个类型
    if (categories.value && categories.value.length > 0) {
      selectedCategory.value = categories.value[0]
      loadServices()
    }
  } finally {
    loading.value = false
  }
}

/**
 * 获取默认分类数据（确保15个分类）
 */
const getDefaultCategories = () => {
  return [
    { id: 1, name: '个人外勤', icon: '💼' },
    { id: 2, name: '个人会计', icon: '📊' },
    { id: 3, name: '疑难杂症', icon: '🔧' },
    { id: 4, name: '列表', icon: '📋' },
    { id: 5, name: '银行开户', icon: '🏦' },
    { id: 6, name: '地址', icon: '📍' },
    { id: 7, name: '节税返税', icon: '💰' },
    { id: 8, name: '资质实用', icon: '📜' },
    { id: 9, name: '人员挂靠', icon: '👥' },
    { id: 10, name: '资质许可', icon: '📄' },
    { id: 11, name: '电销数据', icon: '📞' },
    { id: 12, name: '出报告', icon: '📈' },
    { id: 13, name: '知识产权', icon: '📝' },
    { id: 14, name: '信用修复', icon: '🔄' },
    { id: 15, name: '认证', icon: '✔️' }
  ]
}


/**
 * 处理分类点击
 */
const handleCategoryClick = (category) => {
  selectedCategory.value = category
  loadServices()
}

/**
 * 加载服务列表
 */
const loadServices = async () => {
  if (!selectedCategory.value) return
  
  try {
    loading.value = true
    const params = {
      category_id: selectedCategory.value.id,
      province: currentProvince.value,
      city: currentCity.value
    }
    
    console.log('搜索服务参数:', params)
    const result = await localServiceAPI.searchServices(params)
    console.log('搜索服务结果:', result)
    
    if (result.success) {
      services.value = result.data?.items || []
    } else {
      services.value = []
      uni.showToast({
        title: result.message || '加载服务失败',
        icon: 'none'
      })
    }
  } catch (error) {
    console.error('加载服务列表失败:', error)
    services.value = []
    uni.showToast({
      title: '网络连接失败',
      icon: 'none'
    })
  } finally {
    loading.value = false
  }
}


/**
 * 省份选择处理
 */
const onProvinceChange = (e) => {
  selectedProvinceIndex.value = e.detail.value
  const selectedProvince = provinces[e.detail.value]
  currentProvince.value = selectedProvince
  
  // 重置城市选择
  selectedCityIndex.value = -1
  currentCity.value = ''
  
  // 更新城市列表
  if (selectedProvince) {
    cities.value = getCitiesByProvince(selectedProvince)
  } else {
    cities.value = ['请先选择省份']
  }
}

/**
 * 城市选择处理
 */
const onCityChange = (e) => {
  selectedCityIndex.value = e.detail.value
  currentCity.value = cities.value[e.detail.value]
}

/**
 * 跳转到服务详情
 */
const goToServiceDetail = (service) => {
  uni.navigateTo({
    url: `/pages/local-services/detail?id=${service.id}`
  })
}


/**
 * 跳转到发布服务页面
 */
const goToPublish = async () => {
  const hasCredit = await CreditChecker.checkLocalServiceCredit({
    fromPage: '/pages/local-services/publish',
    action: '发布本地服务'
  })
  if (!hasCredit) {
    return
  }
  uni.navigateTo({
    url: '/pages/local-services/publish'
  })
}

/**
 * 跳转到我的发布页面
 */
const goToMyListings = () => {
  // 检查登录状态
  const token = uni.getStorageSync('token')
  if (!token) {
    uni.showModal({
      title: '提示',
      content: '请先登录后查看我的发布',
      success: (res) => {
        if (res.confirm) {
          uni.navigateTo({
            url: '/pages/login/login'
          })
        }
      }
    })
    return
  }

  uni.navigateTo({
    url: '/pages/local-services/my-services'
  })
}

/**
 * 切换服务点赞状态
 */
const toggleServiceLike = async (service) => {
  // 检查登录状态
  const token = uni.getStorageSync('token')
  if (!token) {
    uni.showModal({
      title: '提示',
      content: '请先登录后进行点赞',
      success: (res) => {
        if (res.confirm) {
          uni.navigateTo({
            url: '/pages/login/login'
          })
        }
      }
    })
    return
  }

  try {
    const response = await localServiceAPI.toggleLike(service.id)
    if (response.success) {
      // 使用后端返回的准确数据更新本地状态
      service.is_liked = response.data.liked
      service.like_count = response.data.like_count || 0
    } else {
      uni.showToast({
        title: response.message || '操作失败',
        icon: 'none'
      })
    }
  } catch (error) {
    console.error('点赞操作失败:', error)
    uni.showToast({
      title: '网络错误',
      icon: 'none'
    })
  }
}
</script>

<style scoped>
.local-services-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-bottom: 160rpx;
}

.categories-container {
  padding-top: 20rpx;
  padding-bottom: 20rpx;
}

.categories-grid {
  padding: 20rpx;
  display: grid;
  grid-template-columns: repeat(5, 1fr);
  gap: 12rpx;
  max-height: 800rpx;
  overflow-y: auto;
}

.category-item {
  background-color: #ffffff;
  border-radius: 10rpx;
  padding: 18rpx 8rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.06);
  transition: all 0.3s ease;
  min-height: 90rpx;
  position: relative;
}

.category-item:active {
  transform: scale(0.95);
  background-color: #f8f9fa;
}

.category-icon {
  font-size: 24rpx;
  margin-bottom: 6rpx;
  line-height: 1;
}

.category-name {
  font-size: 18rpx;
  color: #333;
  text-align: center;
  font-weight: 500;
  line-height: 1.2;
  word-break: break-all;
}

.bottom-actions {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #ffffff;
  padding: 20rpx 30rpx;
  border-top: 1rpx solid #e5e5e5;
  display: flex;
  gap: 20rpx;
}

.action-btn {
  flex: 1;
  height: 88rpx;
  border-radius: 44rpx;
  font-size: 32rpx;
  font-weight: 600;
  border: none;
  display: flex;
  align-items: center;
  justify-content: center;
}

.action-btn.primary {
  background-color: #22c55e;
  color: white;
}

.action-btn.primary:active {
  background-color: #16a34a;
}

.action-btn.secondary {
  background-color: #f59e0b;
  color: white;
}

.action-btn.secondary:active {
  background-color: #d97706;
}

.loading-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(255, 255, 255, 0.8);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.loading-content {
  background-color: rgba(0, 0, 0, 0.7);
  color: white;
  padding: 20rpx 40rpx;
  border-radius: 10rpx;
}

.loading-text {
  font-size: 28rpx;
}

/* 地理位置筛选样式 */
.location-filter {
  background-color: #ffffff;
  padding: 20rpx;
  margin: 20rpx;
  border-radius: 12rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.06);
}

.filter-section {
  display: flex;
  flex-direction: column;
  gap: 20rpx;
}

.filter-label {
  font-size: 28rpx;
  font-weight: 600;
  color: #333;
}

.pickers-row {
  display: flex;
  gap: 20rpx;
  align-items: center;
}

.picker-wrapper {
  flex: 1;
  height: 88rpx;
  border: 1rpx solid #e5e5e5;
  border-radius: 8rpx;
  box-sizing: border-box;
}

.form-picker {
  width: 100%;
  height: 100%;
}

.picker-content {
  width: 100%;
  height: 88rpx;
  padding: 0 20rpx;
  display: flex;
  align-items: center;
  justify-content: space-between;
  box-sizing: border-box;
  background-color: #ffffff;
}

.picker-text {
  font-size: 28rpx;
  color: #333;
  flex: 1;
  height: 88rpx;
  line-height: 88rpx;
}

.picker-text.placeholder {
  color: #999;
}

.arrow {
  font-size: 24rpx;
  color: #999;
  height: 88rpx;
  line-height: 88rpx;
}

/* 服务列表样式 */
.services-container {
  margin: 20rpx;
  background-color: #ffffff;
  border-radius: 12rpx;
  overflow: hidden;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.06);
}

.services-header {
  padding: 20rpx;
  background-color: #f8f9fa;
  border-bottom: 1rpx solid #e9ecef;
  display: flex;
  align-items: center;
  gap: 10rpx;
}

.header-title {
  font-size: 30rpx;
  font-weight: 600;
  color: #333;
}

.header-count {
  font-size: 24rpx;
  color: #6c757d;
}

.services-list {
  /* 移除高度限制，让内容自然展开 */
}

.service-item {
  display: flex;
  padding: 20rpx;
  border-bottom: 1rpx solid #f1f3f4;
  transition: background-color 0.2s;
  align-items: flex-start;
}

.service-item:last-child {
  border-bottom: none;
}

.service-item:active {
  background-color: #f8f9fa;
}

.service-image {
  width: 140rpx;
  height: 100rpx;
  border-radius: 8rpx;
  margin-right: 20rpx;
  flex-shrink: 0;
  background-color: #f5f5f5;
}

.service-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 10rpx;
}

.service-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  gap: 10rpx;
}

.service-title {
  font-size: 28rpx;
  font-weight: 600;
  color: #333;
  line-height: 1.3;
  flex: 1;
  overflow: hidden;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.service-contact {
  display: flex;
  align-items: center;
  gap: 5rpx;
  font-size: 24rpx;
  color: #666;
  margin-top: 5rpx;
}

.contact-label {
  color: #666;
}

.contact-name {
  color: #333;
  font-weight: 500;
}

.service-location {
  display: flex;
  align-items: center;
  gap: 8rpx;
  margin-top: 10rpx;
}

.location-icon {
  font-size: 20rpx;
  color: #999;
}

.location-text {
  font-size: 24rpx;
  color: #666;
}

/* 互动操作区域样式 */
.service-actions {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-top: 10rpx;
}

.action-stats {
  display: flex;
  align-items: center;
  gap: 15rpx;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 4rpx;
  background-color: #f8f9fa;
  padding: 4rpx 8rpx;
  border-radius: 12rpx;
}

.stat-icon {
  font-size: 20rpx;
  color: #666;
}

.stat-count {
  font-size: 20rpx;
  color: #666;
  font-weight: 500;
}

/* 点赞操作样式 */
.like-action {
  flex-shrink: 0;
}

.like-button {
  display: flex;
  align-items: center;
  gap: 6rpx;
  padding: 8rpx 12rpx;
  background-color: #f8f9fa;
  border-radius: 20rpx;
  border: 1rpx solid #e9ecef;
  transition: all 0.3s ease;
}

.like-button:active {
  transform: scale(0.95);
}

.like-button.liked {
  background-color: #fee2e2;
  border-color: #ef4444;
}

.like-icon {
  font-size: 24rpx;
  color: #666;
  transition: all 0.3s ease;
}

.like-button.liked .like-icon {
  color: #ef4444;
  animation: heartBeat 0.6s ease;
}

.like-count {
  font-size: 22rpx;
  color: #333;
  font-weight: 500;
  min-width: 20rpx;
  text-align: center;
}

/* 点赞动画 */
@keyframes heartBeat {
  0% { transform: scale(1); }
  14% { transform: scale(1.2); }
  28% { transform: scale(1); }
  42% { transform: scale(1.2); }
  70% { transform: scale(1); }
}

.service-tags {
  display: flex;
  gap: 8rpx;
  flex-shrink: 0;
}

.tag {
  font-size: 18rpx;
  padding: 2rpx 6rpx;
  border-radius: 3rpx;
  color: white;
  line-height: 1.2;
}

.tag.verified {
  background-color: #22c55e;
}

.tag.deposit {
  background-color: #f59e0b;
}

.no-services {
  padding: 60rpx 20rpx;
  text-align: center;
}

.no-services-text {
  font-size: 28rpx;
  color: #999;
}

/* 响应式适配 */
/* 选中状态样式 */
.category-active {
  background-color: #22c55e !important;
  transform: scale(0.95);
}

.category-active .category-name {
  color: white !important;
  font-weight: 600;
}

/* 针对极小屏幕（小于320px）的适配 */
@media screen and (max-width: 320px) {
  .categories-grid {
    grid-template-columns: repeat(4, 1fr);
    gap: 10rpx;
    padding: 15rpx;
  }
  
  .category-item {
    padding: 15rpx 6rpx;
    min-height: 80rpx;
  }
  
  .category-icon {
    font-size: 20rpx;
  }
  
  .category-name {
    font-size: 16rpx;
  }
  
  .pickers-row {
    flex-direction: column;
    gap: 15rpx;
  }
  
  .picker-wrapper {
    width: 100%;
  }
}
</style>
